package com.yyjj.hangqing.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.aries.ui.view.title.TitleBarView;
import com.tencent.sonic.sdk.SonicConfig;
import com.tencent.sonic.sdk.SonicEngine;
import com.tencent.sonic.sdk.SonicSession;
import com.tencent.sonic.sdk.SonicSessionConfig;
import com.yyjj.hangqing.R;
import com.yyjj.hangqing.api.Api;

import tech.com.commoncore.base.BaseTitleActivity;
import tech.com.commoncore.constant.ApiConstant;
import tech.com.commoncore.utils.brower.SonicJavaScriptInterface;
import tech.com.commoncore.utils.brower.SonicRuntimeImpl;
import tech.com.commoncore.utils.brower.SonicSessionClientImpl;

@Route(path = "/hq/FundH5")
public class FundH5DetailActivity extends BaseTitleActivity {
    public static final String CODE = "symbol";
    private String url = ApiConstant.BASE_URL+Api.HUOQIBAO_DETAIL_H5;
    private String symbol;
    WebView webView;
    ProgressBar progressWeb;
    private SonicSession sonicSession;
    TitleBarView titleBar;
    public static final String NAME = "name";
    private String name;
    @Override
    public int getContentLayout() {
        return R.layout.activity_brower;
    }
    @Override
    public void setTitleBar(TitleBarView titleBar) {
        this.titleBar=titleBar;
    }
    @Override
    public void beforeSetContentView() {
        super.beforeSetContentView();
        symbol = getIntent().getStringExtra(CODE);
        name = getIntent().getStringExtra(NAME);
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        webView = findViewById(tech.com.commoncore.R.id.webview);
        progressWeb = findViewById(tech.com.commoncore.R.id.progress_web);


        titleBar.setTitleMainText(name).setTextColor(Color.WHITE);

        // init sonic engine if necessary, or maybe u can do this when application created
        if (!SonicEngine.isGetInstanceAllowed()) {
            SonicEngine.createInstance(new SonicRuntimeImpl(getApplication()), new SonicConfig.Builder().build());
        }

        SonicSessionClientImpl sonicSessionClient = null;

        // if it's sonic mode , startup sonic session at first time
        // sonic mode
        SonicSessionConfig.Builder sessionConfigBuilder = new SonicSessionConfig.Builder();
        sessionConfigBuilder.setSupportLocalServer(true);

        // if it's offline pkg mode, we need to intercept the session connection


        // create sonic session and run sonic flow  "https://d.wanjinig.cn/home/page/sinaFund?symbol=004398"
        sonicSession = SonicEngine.getInstance().createSession(url+symbol, sessionConfigBuilder.build());
        if (null != sonicSession) {
            sonicSession.bindClient(sonicSessionClient = new SonicSessionClientImpl());
        } else {
            // this only happen when a same sonic session is already running,
            // u can comment following codes to feedback as a default mode.
            // throw new UnknownError("create session fail!");
            //            Toast.makeText(this, "create sonic session fail!", Toast.LENGTH_LONG).show();
        }
        Intent intent = getIntent();

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
//                ViewUtil.hideHtmlContent(view);  //过滤关键字
                if (sonicSession != null) {
                    sonicSession.getSessionClient().pageFinish(url);
                }
            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                String url = request.getUrl().toString();
                if (!TextUtils.isEmpty(url) && url.endsWith(".apk")) {
                    downloadByBrowser(url);
                }
                return !(url.startsWith("http") || url.startsWith("https"));
            }

            @TargetApi(21)
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return shouldInterceptRequest(view, request.getUrl().toString());
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                if (sonicSession != null) {
                    return (WebResourceResponse) sonicSession.getSessionClient().requestResource(url);
                }
                return null;
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {


                if (newProgress == 100) {
                    progressWeb.setVisibility(View.GONE); // 加载完毕进度条消失
                } else {
                    progressWeb.setProgress(newProgress); // 更新进度
                }
                super.onProgressChanged(view, newProgress);
            }

        });

        WebSettings webSettings = webView.getSettings();

        // add java script interface
        // note:if api level lower than 17(android 4.2), addJavascriptInterface has security
        // issue, please use x5 or see https://developer.android.com/reference/android/webkit/
        // WebView.html#addJavascriptInterface(java.lang.Object, java.lang.String)
        webSettings.setJavaScriptEnabled(true);
        webView.removeJavascriptInterface("searchBoxJavaBridge_");
        intent.putExtra(SonicJavaScriptInterface.PARAM_LOAD_URL_TIME, System.currentTimeMillis());
        webView.addJavascriptInterface(new SonicJavaScriptInterface(sonicSessionClient, intent), "sonic");
        webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        // init webview settings
        webSettings.setAllowContentAccess(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);


        // webview is ready now, just tell session client to bind
        if (sonicSessionClient != null) {
            sonicSessionClient.bindWebView(webView);
            sonicSessionClient.clientReady();
        } else { // default mode
            webView.loadUrl(url+symbol);
        }

        //解决图片不显示
        webSettings.setBlockNetworkImage(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    }

    private void downloadByBrowser(String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        intent.setData(Uri.parse(url));
        startActivity(intent);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        if (null != sonicSession) {
            sonicSession.destroy();
            sonicSession = null;
        }
        super.onDestroy();
    }



}



